package com.sgb.kjwl.view.ui.activity.self.userInfo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.gyf.barlibrary.ImmersionBar;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityVerificationCodeLogin3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.kjwl.utils.Constants;
import com.sgb.link.utils.SizeUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.widget.SimpleCountDownTimer;
import com.sgb.kjwl.viewmodel.self.VerificationCodeLoginModel3;
import com.sgb.link.router.PathLogin;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

/**
 * 登录界面
 */
@Route(path = PathLogin.VerificationCodeLoginActivity)
public class VerificationCodeLoginActivity extends AppActivity {

    private ActivityVerificationCodeLogin3Binding binding;
    @Inject
    VerificationCodeLoginModel3 viewModel;

    private boolean isCheck = false;
    private boolean ispwdLogin = true; //是否是密码登录
    public boolean isJump;
    private boolean eyeStatus;//默认闭眼
    public int jump_address;


    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    public static void start(Context context, boolean isJump) {
        Intent intent = new Intent(context, VerificationCodeLoginActivity.class);
        intent.putExtra("isJump", isJump);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, VerificationCodeLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, int jump_address) {
        Intent intent = new Intent(context, VerificationCodeLoginActivity.class);
        intent.putExtra("jump_address", jump_address);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (immersionBar != null){
            immersionBar.transparentStatusBar().statusBarDarkFont(statusBarDark())
                    .fitsSystemWindows(false)
                    .keyboardEnable(false)
                    .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN).init();
        }
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(VerificationCodeLoginActivity.this, R.layout.activity_verification_code_login3);
        binding.setViewModel(viewModel);
    }

    @Override
    protected void init() {
        selectBox();
        initShanyan();
        ARouter.getInstance().inject(this);
        isJump = getIntent().getBooleanExtra("isJump", false);
        jump_address = getIntent().getIntExtra("jump_address", 0);
        binding.tvGetCodeBtn.setOnClickListener(this);
        binding.ivCheckBox.setOnClickListener(this);
//        binding.tvPwdLogin.setOnClickListener(this);
        binding.tvLoginBtn.setOnClickListener(this);

        binding.tvCodeBtn.setOnClickListener(this);
        binding.tvPwdBtn.setOnClickListener(this);

        binding.loginQuick.setOnClickListener(this);
        binding.fogPwd.setOnClickListener(this);
        binding.signBtn.setOnClickListener(this);
        binding.rlEye.setOnClickListener(this);
        binding.tvPwd.setOnClickListener(this);
        binding.tvSmsCode.setOnClickListener(this);
        binding.barLayout.ivBack.setOnClickListener(this);
        setSpan(binding.tvUserProtocol);

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) binding.llTitle.getLayoutParams();
        lp.topMargin = ImmersionBar.getStatusBarHeight(this) + SizeUtils.dp2px(28);
        binding.llTitle.setLayoutParams(lp);

        initLoginView();
        binding.ivClean.setOnClickListener(this);
        binding.etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    binding.ivClean.setVisibility(View.GONE);
                } else {
                    binding.ivClean.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void setSpan(TextView tvUserProtocol) {
        SpannableStringBuilder protocol = new SpannableStringBuilder(getResources().getString(R.string.user_protocol));
        protocol.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.LICENCE_URL));
                WebActivity.start(VerificationCodeLoginActivity.this);
            }
        }, 7, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        protocol.setSpan(new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.color_title_big));//设置颜色
                ds.setUnderlineText(false);//去掉下划线
            }
        }, 7, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        protocol.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.POLICY_URL));
                WebActivity.start(VerificationCodeLoginActivity.this);
            }
        }, 16, protocol.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        protocol.setSpan(new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(getResources().getColor(R.color.color_title_big));//设置颜色
                ds.setUnderlineText(false);//去掉下划线
            }
        }, 16, protocol.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvUserProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        tvUserProtocol.setText(protocol);
        tvUserProtocol.setHighlightColor(Color.TRANSPARENT);
    }

    /**
     * 初始化登录样式布局
     */
    private void initLoginView() {
        if (ispwdLogin) {
            binding.llPwdLogin.setVisibility(View.VISIBLE);
            binding.llCodeLogin.setVisibility(View.GONE);
            binding.tvCodeBtn.setVisibility(View.GONE);
            binding.tvPwdBtn.setVisibility(View.GONE);
            binding.tvPwd.setTextColor(getResources().getColor(R.color.color_gold));
            binding.tvPwd.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            binding.tvSmsCode.setTextColor(getResources().getColor(R.color.color_tab_three));
            binding.tvSmsCode.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            binding.fogPwd.setVisibility(View.VISIBLE);
            binding.tVTitle.setText("密码登录");
        } else {
            binding.llPwdLogin.setVisibility(View.GONE);
            binding.llCodeLogin.setVisibility(View.VISIBLE);
            binding.tvCodeBtn.setVisibility(View.GONE);
            binding.tvPwdBtn.setVisibility(View.GONE);
            binding.tvSmsCode.setTextColor(getResources().getColor(R.color.color_gold));
            binding.tvSmsCode.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            binding.tvPwd.setTextColor(getResources().getColor(R.color.color_tab_three));
            binding.tvPwd.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            binding.fogPwd.setVisibility(View.INVISIBLE);
            binding.tVTitle.setText("验证码登录");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_quick:
                jumpLogin();
                break;
            case R.id.fog_pwd: //忘记密码
                ForgetActivity.start(this, getResources().getString(R.string.find_pwd));
                break;
            case R.id.sign_btn: //注册
                RegisterActivity3.start(this);
                break;
            case R.id.iv_back: //返回
                finish();
                break;
            case R.id.tv_get_code_btn: //获取验证码
                codeValidation();
                break;
            case R.id.iv_clean: //清空输入框内容
                binding.etCode.setText("");
                break;
            case R.id.iv_check_box: //阅读协议
                selectBox();
                break;
            //验证码登录
            case R.id.tv_code_btn:
            case R.id.tv_sms_code:
                if (ispwdLogin){
                    ispwdLogin = false;
                    initLoginView();
                }
                break;
            //密码登录
            case R.id.tv_pwd_btn:
            case R.id.tv_pwd://密码登录
                if (!ispwdLogin){
                    ispwdLogin = true;
                    initLoginView();
                }
                break;
            case R.id.tv_agreement:
//                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEB_FILE, "平台服务条款"));
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.LICENCE_URL));
                WebActivity.start(VerificationCodeLoginActivity.this);
                break;
            case R.id.tv_privacy:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.POLICY_URL));
                WebActivity.start(VerificationCodeLoginActivity.this);
                break;
            case R.id.tv_login_btn:
                if (TextUtils.isEmpty(binding.etMobile.getText())) {
                    MToast.showToast(VerificationCodeLoginActivity.this, "请输入手机号");
                    return;
                }
                if (!CheckUtils.isMobileNum(binding.etMobile.getText().toString())) {
                    MToast.showToast(VerificationCodeLoginActivity.this, "请输入正确手机格式");
                    return;
                }
                if (ispwdLogin) {
                    if (TextUtils.isEmpty(binding.etPwd.getText())) {
                        MToast.showToast(VerificationCodeLoginActivity.this, "请输入密码");
                        return;
                    }
                    if (binding.etPwd.getText().length() < 6 || binding.etPwd.getText().length() > 18) {
                        MToast.showToast(VerificationCodeLoginActivity.this, "密码长度为6-18位");
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(binding.etCode.getText())) {
                        MToast.showToast(VerificationCodeLoginActivity.this, "请输入验证码");
                        return;
                    }
                }
                if (!isCheck) {
                    MToast.showToast(VerificationCodeLoginActivity.this, "请勾选经营帮用户协议");
                    return;
                }
                if (ispwdLogin) {
                    viewModel.pwdLoginModel(binding.etMobile.getText().toString(), binding.etPwd.getText().toString());
                } else {
                    viewModel.loginModel(binding.etMobile.getText().toString(), binding.etCode.getText().toString());
                }
                break;
            case R.id.rl_eye:
                eyeStatus = !eyeStatus;
                if (eyeStatus) {
                    binding.ivEye.setImageDrawable(getResources().getDrawable(R.mipmap.icon_eye_open));
                    binding.etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    binding.ivEye.setImageDrawable(getResources().getDrawable(R.mipmap.icon_eye_close));
                    binding.etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                binding.etPwd.setSelection(binding.etPwd.getText().length());
                break;
        }
    }

    private void selectBox() {
        isCheck = !isCheck;
        if (isCheck) {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_on));
        } else {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_off));
        }
    }

    public void setEnable(boolean enable) {
        binding.tvLoginBtn.setEnabled(enable);
    }

    private void codeValidation() {
        if (TextUtils.isEmpty(binding.etMobile.getText())) {
            MToast.showToast(VerificationCodeLoginActivity.this, "请输入手机号");
            return;
        }
        if (!CheckUtils.isMobileNum(binding.etMobile.getText().toString())) {
            MToast.showToast(VerificationCodeLoginActivity.this, "请输入正确手机格式");
            return;
        }
        viewModel.getCodeModel(binding.etMobile.getText().toString());
    }

    /**
     * 倒计时
     */
    public void starTime() {
        SimpleCountDownTimer mCountDownTimerUtils = new SimpleCountDownTimer(VerificationCodeLoginActivity.this, binding.tvGetCodeBtn, 60000, 1000,false); //倒计时1分钟
        mCountDownTimerUtils.start();
    }

    /**
     * 验证码登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        String event_shopping_type = SharedPreferenceUtil.getInstance().getString("EVENT_SHOPPING_TYPE", "");
        OneKeyLoginManager.getInstance().finishAuthActivity();
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
//        if (!TextUtils.isEmpty(event_shopping_type)) {
//            if (event_shopping_type.equals("event_shopping_list")) {
//                loginEvent.setMessageTag(EventConstant.EVENT_SHOPPING_LIST_LOGIN);
//            } else {
//                loginEvent.setMessageTag(EventConstant.EVENT_SHOPPING_LOGIN);
//            }
//        } else {
        loginEvent.setMessageTag(jump_address);
//        }
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().post(loginEvent);

//        Intent intent = new Intent();
//        intent.putExtra("showPage", "FRAGMENT_SELF");
//        MainActivity.start(getActivity(), intent);

    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }


    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            //VerificationCodeLoginActivity.start(getActivity());
            Toast.makeText(getApplicationContext(), "获取电话号码失败,请插入手机卡或开启移动数据后再试", Toast.LENGTH_SHORT).show();
            initShanyan();
        }
    }


    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
               /* if (code != 1000) {
                    VerificationCodeLoginActivity.start(MainActivity.this);
                }*/
            }
        }, new OneKeyLoginListener() {

            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    private final static int SPACE_TIME = 60 * 1000;//2次点击的间隔时间，单位ms
    private static long lastClickTime;

    public boolean isDoubleClick() {
        long currentTime = System.currentTimeMillis();
        boolean isClick;
        if (currentTime - lastClickTime > SPACE_TIME) {
            isClick = false;
        } else {
            isClick = true;
        }
        lastClickTime = currentTime;
        return isClick;
    }
}
